# coding:utf8
"""
python中的链表
"""


# 1.创建链表
class Node:
    def __init__(self, dataval=None):
        self.dataval = dataval
        self.nextval = None

    def __str__(self):
        return self.dataval


class SlinkedList:
    def __init__(self):
        self.headval = None

    # 插入在开头位置，链表左侧
    def add_left(self, newdata):
        NewNode = Node(newdata)
        NewNode.nextval = self.headval
        self.headval = NewNode

    def append(self, newdata):
        NewNode = Node(newdata)
        # 判断是否原链表没有节点，如果没有，该节点就是第一个节点
        if self.headval is None:
            self.headval = NewNode
            return
        laste = self.headval
        # while执行后，laste.nextval如果一直存在，遍历直至原链表最后一个
        while (laste.nextval):
            laste = laste.nextval
        # 在原最后一个节点之后再续一个节点
        laste.nextval = NewNode

    def insert(self, middle_node, newdata):
        if not middle_node:
            print("middle_node not exist")
            return
        NewNode = Node(newdata)
        NewNode.nextval = middle_node.nextval
        middle_node.nextval = NewNode

    def remove(self, removekey):
        headval = self.headval
        print("remove headval:{}".format(headval))
        if not headval:
            print("not headval 1")
            if (headval.dataval == removekey):
                self.headval = headval.nextval
                headval = None
                return
        while not headval:
            print("not headval 2")
            if headval.dataval == removekey:
                break
            prev = headval
            headval = headval.nextval

        if headval is None:
            print("not headval 3")
            return
        prev = headval
        prev.nextval = headval.nextval

        headval = None

    def show(self):
        printval = self.headval
        while printval:
            print(printval.dataval)
            printval = printval.nextval


li = SlinkedList()
print('li', li)
li.headval = Node('Mon')
print(li.headval)
e2 = Node("Tue")
e3 = Node("Wed")
print(e2, e3)

# 连接第一个第二个节点
li.headval.nextval = e2
# 连接第二个第三个节点
e2.nextval = e3
print(e2.nextval)
print(e2.nextval.dataval)

print('*' * 50)
# 2.遍历链表
# 在链表末尾添加一个新的node
# li.add_left('Sun')
li.insert(li.headval.nextval, 'Fri')
print(li.show())
print('*' * 50)
print(li.remove('Web'))
print(li.show())
